package com.tj.bo.user.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.google.common.collect.Lists;
import com.tj.bo.common.conf.constant.RedisKey;
import com.tj.bo.common.conf.constant.RedisTimeConstant;
import com.tj.bo.product.client.ProductService;
import com.tj.bo.product.client.vo.Product;
import com.tj.bo.product.client.vo.ProductListVo;
import com.tj.bo.user.client.UserProductService;
import com.tj.bo.user.client.enums.TriggerTypeEnum;
import com.tj.bo.user.client.vo.input.UserProductOdds;
import com.tj.bo.user.server.entity.UserProductOddsEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @program: binary-option
 * @description
 * @author: binary
 * @create: 2020-07-31 17:29
 **/
@Service
public class UserProductServiceImpl extends UserBaseService implements UserProductService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserProductServiceImpl.class);


    @Autowired
    private RedisClient redisClient;
    @Autowired
    private ProductService productService;

    @Override
    public ProductListVo getAllActiveProductList(String userCode, boolean isGrey) {
        ProductListVo productListVo = productService.getAllActiveProductList();
        List<Product> products = productListVo.getProducts();
        LOGGER.info("== 获取用户的产品列表 ==,products:{}", JSON.toJSONString(productListVo));
        for (Product product : products) {
            product.setOdds(this.getSettlementProfit(product.getProductCode(), userCode, new BigDecimal(product.getCurrentOdds()), isGrey).toPlainString());
        }
        productListVo.setProducts(products);
        LOGGER.info("============ productListVo :{} =========", JSONObject.toJSONString(productListVo));
        return productListVo;
    }

    @Override
    public Product getProductByCode(String productCode, String userCode, boolean isGrey) {
        Product product = productService.getProductByCode(productCode);
        if (product != null) {
            product.setOdds(this.getSettlementProfit(product.getProductCode(), userCode, new BigDecimal(product.getOdds()), isGrey).toString());
        }
        return product;
    }

    @Override
    public boolean insertUserProductService(UserProductOdds userProductOdds) {

        //按照设计 若没有触发过用户规则，即使触发大盘规则也不落用户赔率表
        //触发过用户规则的才走以下逻辑，用户赔率以此表为准
        if (userProductOdds != null) {
            UserProductOddsEntity entity = new UserProductOddsEntity();
            BeanUtils.copyProperties(userProductOdds, entity);
            List<UserProductOddsEntity> userProductOddsEntities = userProductOddsDao.getByUserCodeAndProductCode(userProductOdds.getUserCode(), userProductOdds.getProductCode(), null);

            if (userProductOdds.getTriggerType() == TriggerTypeEnum.MARKET_TRIGGER.getCode()) {
                if (CollectionUtils.isEmpty(userProductOddsEntities)) {
                    return true;
                }

                for (UserProductOddsEntity userProductOddsEntity : userProductOddsEntities) {
                    userProductOddsEntity.setDeleted(true);
                    userProductOddsDao.updateByPrimaryKey(userProductOddsEntity);
                }

                //历史数据为0的情况
                BigDecimal theoryOdds = new BigDecimal(userProductOddsEntities.get(0).getTheoryOdds());
                if (theoryOdds.compareTo(BigDecimal.ZERO) == 0) {
                    theoryOdds = new BigDecimal(userProductOddsEntities.get(0).getOdds());
                }
                //当前用户赔率=上一次用户赔率+(当前大盘赔率-上一次大盘赔率)
                BigDecimal userTheoryCurrentOdds = theoryOdds.add(new BigDecimal(userProductOdds.getMarketOdds()).subtract(new BigDecimal(userProductOddsEntities.get(0).getMarketOdds())));
                BigDecimal userCurrentOdds = userTheoryCurrentOdds;
                if (userTheoryCurrentOdds.compareTo(new BigDecimal(userProductOdds.getProductMiniOdds())) < 0) {
                    userCurrentOdds = new BigDecimal(userProductOdds.getProductMiniOdds());
                }
                if (userTheoryCurrentOdds.compareTo(new BigDecimal(userProductOdds.getProductOdds())) > 0) {
                    userCurrentOdds = new BigDecimal(userProductOdds.getProductOdds());
                }
                entity.setTheoryOdds(userTheoryCurrentOdds.toPlainString());
                entity.setOdds(userCurrentOdds.toPlainString());
            } else {
                for (UserProductOddsEntity userProductOddsEntity : userProductOddsEntities) {
                    userProductOddsEntity.setDeleted(true);
                    userProductOddsDao.updateByPrimaryKey(userProductOddsEntity);
                }
                if (CollectionUtils.isNotEmpty(userProductOddsEntities)) {
                    if (new BigDecimal(userProductOddsEntities.get(0).getTheoryOdds()).compareTo(BigDecimal.ZERO) == 0) {
                        entity.setTheoryOdds(userProductOdds.getOdds());
                    } else {
                        BigDecimal theoryOdds = new BigDecimal(userProductOddsEntities.get(0).getTheoryOdds()).add(new BigDecimal(userProductOdds.getOdds()).subtract(new BigDecimal(userProductOddsEntities.get(0).getOdds())));
                        entity.setTheoryOdds(theoryOdds.toPlainString());
                    }
                } else {
                    entity.setTheoryOdds(userProductOdds.getOdds());
                }
            }
            entity.setMarketOdds(new BigDecimal(userProductOdds.getMarketOdds()).toPlainString());
            userProductOddsDao.insert(entity);
            redisClient.set(RedisKey.BINARY_OPTION_PRODUCT_USER_ODDS, entity.getOdds(), RedisTimeConstant.ONE_MONTH, userProductOdds.getProductCode(), userProductOdds.getUserCode());
        }
        return true;
    }

    @Override
    public void insertUserProductServiceV2(String userCode, String productCode, BigDecimal changeValue, String ruleName, String remark, Date expireDate) {
        if (StringUtils.isEmpty(userCode) || StringUtils.isEmpty(productCode) || changeValue == null) {
            return;
        }

        if (expireDate == null) {
            expireDate = DateUtil.getDate("2099-12-31", "yyyy-MM-dd");
        }

        if (changeValue.doubleValue() > 0) {
            changeValue = BigDecimal.ZERO;
        }
        List<UserProductOddsEntity> userProductOddsEntities = userProductOddsDao.selectUserProductOddsByExpireDate(userCode, productCode, new Date());
        if (CollectionUtils.isNotEmpty(userProductOddsEntities)) {
            UserProductOddsEntity userProductOddsEntity = userProductOddsEntities.get(0);
            if (DateUtil.diffDate(new Date(), userProductOddsEntity.getGmtCreate()) == 0
                    && userProductOddsEntity.getRelativeOdds().compareTo(changeValue) < 0) {
                LOGGER.info("insertUserProductServiceV2,当天pl只降不升,userCode:{},productCode:{},curr:{},changeValue:{}", userCode, productCode, userProductOddsEntity.getRelativeOdds(), changeValue);
                return;
            }
        }

        //使老数据失效
        Integer num = userProductOddsDao.invalidateUserProductOdds(userCode, productCode, new Date());
        //插入新数据
        UserProductOddsEntity entity = new UserProductOddsEntity();
        entity.setUserCode(userCode);
        entity.setProductCode(productCode);
        entity.setRelativeOdds(changeValue);
        entity.setExpireDate(expireDate);
        entity.setTriggerType(TriggerTypeEnum.USER_TRIGGER.getCode());
        entity.setRuleName(ruleName);
        entity.setRemark(remark);
        userProductOddsDao.insert(entity);
        LOGGER.info("insertUserProductServiceV2,新odd设置成功,userCode:{},productCode:{},changeValue:{},num:{}", userCode, productCode, changeValue, num);
    }

    @Override
    public List<UserProductOdds> getByUserProductList(String productCode) {

        List<UserProductOddsEntity> byUserProductList = userProductOddsDao.getByUserProductList(productCode);
        List<UserProductOdds> userProductOddsList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(byUserProductList)) {
            for (UserProductOddsEntity userProductOddsEntity : byUserProductList) {
                UserProductOdds userProductOdds = new UserProductOdds();
                BeanUtils.copyProperties(userProductOddsEntity, userProductOdds);
                userProductOddsList.add(userProductOdds);
            }
        }
        return userProductOddsList;
    }

    /**
     * 获取结算收益率
     *
     * @param productCode
     * @param userCode
     * @param profit      当前大盘值
     * @return
     */
    @Override
    public BigDecimal getSettlementProfit(String productCode, String userCode, BigDecimal profit, boolean isGrey) {
        if (StringUtils.isEmpty(productCode) || StringUtils.isEmpty(userCode)) {
            throw new ApplicationException("Parameter error");
        }
        List<UserProductOddsEntity> userProductOddsEntities;
        if (!isGrey) {
            userProductOddsEntities = userProductOddsDao.selectUserProductOddsByExpireDate(userCode, productCode, new Date());
            if (CollectionUtils.isEmpty(userProductOddsEntities)) {
                return profit;
            }
            if (userProductOddsEntities.get(0).getRelativeOdds() == null) {
                LOGGER.info("=========== 用户赔率为空 userProductOddsEntities:{} ==========", JSONObject.toJSONString(userProductOddsEntities.get(0)));
                return profit;
            }
            return profit.add(userProductOddsEntities.get(0).getRelativeOdds()).setScale(4, BigDecimal.ROUND_HALF_UP);
        } else {
            //灰名单 收益率变更为大盘收益率的60%
            return profit.multiply(new BigDecimal(0.6)).setScale(4, BigDecimal.ROUND_HALF_UP);
        }
    }
}
